<template>
  <div class="flex flex-col h-full bg-white">
    <!-- 搜索栏 -->
    <div class="flex flex-row items-center px-4 py-3">
      <van-search
        v-model="searchText"
        placeholder="搜索"
        shape="round"
        class="flex-1"
        @update:model-value="onUpdateModelValue"
      />
      <van-loading v-if="loading" class="ml-2" />
      <div class="text-primary ml-3 text-sm text-yxt-blue" @click="onCreate">新建</div>
    </div>

    <!-- 列表区域 -->
    <div class="flex-auto overflow-y-auto px-4 h-[300px]">
      <!-- 猜你想找 -->
      <div class="mb-4">
        <h2 class="text-sm font-medium mb-2" v-show="searchText.length === 0">
          猜你想找
        </h2>
        <template v-if="listData.length > 0">
          <div
            v-for="(person, index) in listData"
            :key="index"
            class="flex items-center py-3 border-b border-gray-100"
            @click="onClickBox(person)"
          >
            <van-checkbox
              v-model="person.selected"
              @click.stop="onClickBox(person)"
              class="mr-3"
            />
            <div
              class="w-10 h-10 rounded-full mr-3 flex items-center justify-center text-white text-sm font-medium"
              :style="{
                backgroundColor: getAvatarColor(person.fullname || person.name),
              }"
            >
              {{ getFirstLetter(person.fullname || person.name) }}
            </div>
            <div class="flex-1">
              <div class="text-sm font-medium">
                {{ person.fullname || person.name }}
              </div>
              <div class="text-xs text-gray-500">
                {{ person.des }}
              </div>
            </div>

            <div
              v-if="person.isCustom && !isRecommendList"
              class="flex flex-row items-center gap-2 text-sm text-gray-500"
            >
              <van-icon name="edit" @click.stop="onEdit(person)" />
              <!-- <van-icon name="delete-o" @click.stop="onDelete(person)" /> -->
            </div>
          </div></template
        >

        <div v-else class="text-center text-gray-500 text-sm">
          <van-empty
            :image="searchText.length > 0 ? 'search' : 'default'"
            :description="searchText.length > 0 ? '未搜索到数据' : '暂无数据'"
          />
        </div>
      </div>
    </div>

    <!-- 底部确定按钮 -->
    <div class="px-4 py-3 border-t">
      <van-button type="primary" block :disabled="!hasSelected" @click="handleConfirm">
        确定({{ selectedCount }})
      </van-button>
    </div>

    <!-- 新建发言人 -->
    <van-popup
      v-model:show="showEditView"
      teleport="#minutesPage"
      :lock-scroll="false"
      class="z-index-999"
      round
      position="bottom"
      :style="{ height: '90%' }"
    >
      <internalFormView
        v-if="showEditView"
        :is-edit-model="isEditModel"
        :personInfo="currentEditInfo"
        @confirm="onConfirmCreateInternal"
        @updateSuccess="onUpdateSuccess"
      />
    </van-popup>
  </div>
</template>

<script>
import {
  searchInnerAttendAPI,
  searchRecommendAPI,
  deleteInternalAttendAPI,
} from "@/services/minutes/lateAttender";
import internalFormView from "./internalFormView.vue";
import debounce from "@/utils/debounce";
import { showToast } from "vant";
import { useMinutesStore } from "@/store";
import { mapState } from "pinia";
import { getUserInfo } from "@/utils/auth";
import { showLoadingToast, closeToast, showConfirmDialog } from "vant";

export default {
  name: "SelectInternalPage",
  emits: ["selectInternal", "confirmCreateInternal"],
  components: {
    internalFormView,
  },
  data() {
    return {
      searchText: "",
      selectedPeople: {},
      recommendList: [],
      attendList: [],
      loading: false,
      showEditView: false,
      createAttend: {
        name: "",
        positionName: "",
      },
      isEditModel: false,
      currentEditInfo: {},
    };
  },

  mounted() {
    this.onSearchRecommend();
  },

  computed: {
    ...mapState(useMinutesStore, {
      recordInfo: "getRecord",
    }),

    filteredPeople() {
      if (!this.searchText) return this.peopleList;
      const searchLower = this.searchText.toLowerCase();
      return this.peopleList.filter(
        (person) =>
          person.name.toLowerCase().includes(searchLower) ||
          person.title.toLowerCase().includes(searchLower) ||
          person.department.toLowerCase().includes(searchLower)
      );
    },

    listData() {
      return this.searchText.length > 0 ? this.attendList : this.recommendList;
    },

    isRecommendList() {
      return this.searchText.length === 0;
    },

    selectedCount() {
      return this.listData.filter((person) => person.selected).length;
    },

    hasSelected() {
      return this.selectedCount > 0;
    },
  },

  methods: {
    reloadList() {
      this.onSearchRecommend();
    },
    onRemoveLocalCache(person) {
      this.recommendList = this.recommendList.filter((v) => v.name !== person.name);
      // this.saveCache();
    },
    onClickBox(person) {
      console.log("onClickBox: ", person);
      // 取消其他人的选中状态
      this.attendList.forEach((v) => (v.selected = false));
      this.recommendList.forEach((v) => (v.selected = false));
      // 设置当前选中的状态
      person.selected = true;

      // 更新 selectedPeople
      this.selectedPeople = person; // 只保留当前选中的人员
    },
    handleConfirm() {
      // 将选中状态回调出去
      // 统一一下 猜你喜欢和模糊查询中的id, 新建时不存在则为空
      this.selectedPeople.ssoUserId =
        this.selectedPeople.ssoUserId || this.selectedPeople.id || "";
      this.$emit("selectInternal", this.selectedPeople);
      delete this.selectedPeople.selected;
    },

    onConfirmCreateInternal(v) {
      console.log("onConfirmCreateInternal  来了:", v);
      this.showEditView = false;
      this.$emit("confirmCreateInternal", v);
    },

    onUpdateSuccess(v) {
      console.log("onUpdateSuccess: ", v);
      this.showEditView = false;
      this.reloadList();
    },

    getFirstLetter(name) {
      if (!name) return "";
      return name.charAt(0).toUpperCase();
    },

    getAvatarColor(name) {
      if (!name) return "#ccc";
      const colors = [
        "#1abc9c",
        "#2ecc71",
        "#3498db",
        "#9b59b6",
        "#34495e",
        "#16a085",
        "#27ae60",
        "#2980b9",
        "#8e44ad",
        "#2c3e50",
        "#f1c40f",
        "#e67e22",
        "#e74c3c",
        "#95a5a6",
        "#f39c12",
        "#d35400",
        "#c0392b",
        "#7f8c8d",
      ];

      // 使用名字的 charCode 来确定颜色，这样同名用户会得到相同的颜色
      let hash = 0;
      for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
      }
      return colors[Math.abs(hash) % colors.length];
    },

    async onUpdateModelValue(v) {
      console.log("onUpdateModelValue: ", v);
      if (v.length === 0) return;
      this.loading = true;
      debounce(async () => {
        const { data, code, message } = await searchInnerAttendAPI(v);

        console.log("onUpdateModelValue: ", data, code, message);
        this.loading = false;
        if (code !== 0) {
          showToast(message || "搜索失败");
          return;
        }
        this.attendList = data.datas.map((v) => this.makeListItem(v));
        console.log("onUpdateModelValue: ", v, this.attendList);
      });
    },

    async onSearchRecommend() {
      this.recommendList = [];
      let data = await searchRecommendAPI();
      let recommendList = data.datas || [];
      this.recommendList = recommendList.map((v) => this.makeListItem(v));
      this.searchForSelf();
    },

    async searchForSelf() {
      let { name, ssoUserId } = getUserInfo();
      const { data, code, message } = await searchInnerAttendAPI(name);
      const datas = data.datas || [];
      console.log("searchForSelf: ", data, code, message);

      if (code === 0 && datas.length > 0) {
        let list = datas.filter((v) => v.ssoUserId === ssoUserId);
        // 将第一个结果插入 recommendList
        list = list.map((v) => this.makeListItem(v));
        console.log("searchForSelf list: ", list);
        if (list.length > 0) {
          this.recommendList.unshift(list[0]);
        }
      }
    },

    // 将服务端各种数据统一成一个格式数据
    makeListItem(v) {
      // name userId ssoUserId des isCustom

      const isCustom =
        v.participantType === "EXTERNAL_PARTNER" || v.partnerId?.length > 0;
      return {
        name: v.name,
        userId: v.ssoUserId,
        ssoUserId: v.ssoUserId,
        des: isCustom
          ? this.makeDesByFormData(v.formData)
          : v.deptFullName + " " + v.position,
        formData: v.formData,
        partnerId: v.partnerId,
        isCustom: isCustom,
      };
    },

    makeDesByFormData(v) {
      if (!v) return "";
      const { fieldValues } = v;
      return fieldValues
        .map(({ fieldName, fieldValue }) => `${fieldName}:${fieldValue}`)
        .join("|");
    },

    // 点击创建
    onCreate() {
      this.isEditModel = false;
      this.createAttend = {};
      this.showEditView = true;
    },

    onEdit(person) {
      console.log("onEdit: ", person);
      this.isEditModel = true;
      this.currentEditInfo = person;
      this.showEditView = true;
    },

    onDelete(person) {
      showConfirmDialog({
        title: "提示",
        message: "确定删除该发言人吗？",
      }).then(() => {
        this.delete(person);
      });
    },

    async delete(person) {
      if (!person.partnerId) return;
      showLoadingToast({ duration: 0 });
      await deleteInternalAttendAPI(person.partnerId);
      closeToast();
      this.reloadList();
    },
  },
};
</script>

<style lang="less" scoped>
.test-view {
  height: 300px;
  width: 100%;
  background-color: red;
  overflow-y: scroll;
}
</style>
